package com.hzaupj.sb;

import com.hzaupj.sb.vo.Hall;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by pengjian_91 on 2015/3/10.
 */
public class HallParse {

    private String url = "http://waimai.meituan.com/home/wssu98hv3m59";

    public List<Hall> getHallList() throws IOException {
        List<Hall> halls = new ArrayList<Hall>();
        Document doc = Jsoup.connect(url).timeout(5000).get();
        Elements eles = doc.select("div").select("[data-title]");
        for(Element element : eles){
            Hall hall = new Hall();
            hall.setName(element.attr("data-title"));
            hall.setBulletinInfo(element.attr("data-bulletin"));
            String[] infos = getInfo(element);
            hall.setId(infos[0]);
            hall.setPicUrl(infos[1]);
            String disInfo = getDisInfo(element);
            hall.setDisList(getDisList(disInfo));
            hall.setDisInfo(disInfo);
            halls.add(hall);
        }
        return halls;
    }

    private List<String[]> getDisList(String disInfo) {
        List<String[]> results = new ArrayList<String[]>();
        String patternStr = "满(\\S*?)元减(\\S*?)元";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher m = pattern.matcher(disInfo);
        while(m.find()){
            String[] dis = new String[2];
            dis[0] = m.group(1);
            dis[1] = m.group(2);
            results.add(dis);
        }

        return results;
    }

    private String[] getInfo(Element element) {
        String[] results = new String[2];
        Elements els = element.select("img").select("[data-rid]");
        for(Element el : els) {
            String id = el.attr("data-rid");
            results[0] = id;
            String url = el.attr("data-src");
            results[1] = url;
        }
        return results;
    }

    private String getDisInfo(Element element) {
        Elements els = element.select("div").select("[class=others]");
        for(Element el : els) {
            return el.data().replaceAll(" ", "");
        }
        return null;
    }
}
